<style>
#pm_dialog .modal-dialog { max-width: 726px;}
#pm_dialog .modal-body > dl { height: 100%;}
#pm_dialog .modal-body > dl > dt { padding: 8px; background: #eee; width: 150px;}
#pm_dialog .modal-body > dl > dd { padding: 8px; }
#pm_dialog .modal-body ul { list-style: none; margin:0px; padding: 0px; }
ul.recentlist {  
        height: 380px;
        overflow: auto;
}
ul.recentlist::-webkit-scrollbar, #pmlist::-webkit-scrollbar {  
        border-radius: 16px;
        width: 6px;
        background: #ddd;
}
ul.recentlist::-webkit-scrollbar-thumb, #pmlist::-webkit-scrollbar-thumb {
        background-color: #aaa;
        border-radius: 16px;
}

ul.recentlist li { line-height: 1.5rem; margin-bottom: 0.1rem; padding: 0.2rem;}
ul.recentlist li:hover { background: #fff; }
ul.recentlist li.active { background: #fff; }
@keyframes pm_flash {
	0% { opacity: 0; } 
	50% { opacity: 1; } 
	100% { opacity: 0; } 
}
#pm_link i.icon-envelope-o.newpm { animation: pm_flash 1s linear infinite; webkit-animation: pm_flash 2s linear; pointer-events: none }
.pm-table { margin-bottom: 0.5rem;}
.pm-left-msg { width: 90%; float: left; background: #DBDBDB; border-radius: 8px; padding: 0.2rem 0.5rem; }
.pm-right-msg { width: 90%; float: right; background: #6FCE71; border-radius: 8px; padding: 0.2rem 0.5rem; }
.pm-right-msg .text-grey { color: #A6EBA7 !important}
.pm-right-msg a.delete { display: none; }
.pm-right-msg:hover a.delete { display: inline; }
.pm-more { font-size: 12px; color: #2786E4; text-align: center; cursor: pointer;}
.pm-count { background: #bbb; padding: 0px 8px; border-radius: 8px; float: right; font-size: 9px; color: #fff;}
</style>

<script src="<?php echo $conf['view_url'];?>js/vue.js<?php echo $static_version;?>"></script>

<!--
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#pm_dialog">Open modal for @mdo</button>
-->

<script type="text/x-template" id="tpl_pm">

<table width="100%" v-if="pm.senduid != user.uid" class="pm-table">
	<tr>
		<td width="36">
                        <a :href="cuser.uid"><img :src="cuser.avatar_url" class="avatar-sm" /></a>
		</td>
		<td>
                        <div class="pm-left-msg">
			        {{ pm.message }} <span class="text-muted small"> - {{ pm.create_date_fmt }}</span>
                        </div>
		</td>
	</tr>
</table>
<table width="100%" class="pm-table"  v-else>
        <tr>
		<td>
                        <div class="pm-right-msg">
                                {{ pm.message }} <span class="text-grey small"> - {{ pm.create_date_fmt }}</span>
                                <a href="javascript:void(0);" @click="delete_pm(pm)" class="m-l-sm delete" style="float: right;">
                                        <i class="icon-remove text-danger"></i>
                                </a>
                        </div>
		</td>
		<td width="36">
                        <a :href="user.uid"><img :src="user.avatar_url" class="avatar-sm" /></a>
		</td>
	</tr>
</table>
</script>

<div class="modal fade" id="pm_dialog" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
  	<div class="modal-content">
  	  <div class="modal-header">
  	  	<button type="button" class="close" data-dismiss="modal">
  	  	        <span aria-hidden="true">&times;</span>
  	  	</button>
                <h5 class="modal-title" style="text-align: center;">{{ cuser.username }}</h5>
  	  </div>
  	  <div class="modal-body" style="width: 724px;">
                <dl class="row">
                        <dt class="vtop">
                                <div class="text-center m-y-1">
                                        <img src="<?php echo $user['avatar_url'];?>" class="avatar" />
                                        <!--<br><?php echo $user['username'];?>-->
                                </div>
                                <ul class="recentlist">
                                        <li v-for="(u,index) in recentlist" @click="change_user(u.uid)" :class="{active: u.uid == cuid}" style="cursor:pointer">
                                                <img :src="user.avatar_url" class="avatar-xs" />{{ u.username }}
                                                <span class="pm-count" v-if="u.count > 0"> {{ u.count }} </span>
                                        </li>
                                </ul>
                        </dt>
                        <dd class="vtop">
                                <div class="pm-more" @click="more_pm()" v-if="have_more_pm"><span class="icon-clock-o"></span> 更多消息</div>
                                <div style="height: 504px; overflow: hidden; display: flex; display: -webkit-flex; flex-direction: column; " id="pmlist_div">
                                        <div id="pmlist" ref="pmlist" style="flex-grow: 0; max-height: 100%; overflow: auto;" >
                                                <ul>
                                                        <li v-for="(pm,index) in pmlist" :pmid="pm.pmid">
                                                                <comp-pm :pm="pm" :is_last="index === pmlist.length - 1" :user="user" :cuser="cuser"></comp-pm>
                                                        </li>
                                                </ul>
                                        </div>
                                        <div style="height: 100px;">
                                                <textarea style="width: 100%; height: 60px;" v-model="textarea" ref="textarea"></textarea>         
                                                <p class="text-left">
                                                        <button @click="create_pm()" type="button" class="btn btn-primary" id="submit" data-loading-text="<?php echo lang('submiting');?>..." style="width: 10rem;"><?php echo lang('confirm');?></button>
                                                </p>
                                        </div>
                                </div>
                        </dd>
                </dl>
  	  </div>
  	</div>
  </div>
</div>

<br>
<br>
<br>
<br>
<br>

<?php if($uid) { ?>

<script>
var user = <?php echo json_encode($user);?>;
var uid = user.uid ? user.uid : 0;  // 我的 uid
var jpm_link = $('#pm_link');
var jpm_icon = jpm_link.find('i.icon-envelope-o');
jpm_link.on('click', function() {
        show_pm_dialog();
});

// 对两个数组进行合并
xn.arrlist_merge = function(arrlist1, arrlist2, k) {
        if(!xn.is_array(arrlist1)) return [];
        if(!xn.is_array(arrlist2)) return arrlist1;
        arrlist2.map(function(v) {
                var r = arrlist1.find(function(v2) { return v2[k] == v[k]});
                if(!r) arrlist1.push(v);
        });
        return arrlist1;
}

// 对数组进行排序
xn.arrlist_sort = function(arrlist, key, asc) {
        if(asc === undefined) asc = true;
        return arrlist.sort(function(a, b) {
                if(a[key] > b[key]) return asc ? 1 : -1;
                if(a[key] < b[key]) return asc ? -1 : 1;
                return 0;
        });
}

// 获取最大 id, 最小 id
xn.arrlist_max = function(arrlist, key) {
        var maxid = 0;
         arrlist.map(function(v) {
                if(v[key] > maxid) {
                        maxid = v[key];
                }
        });
        return maxid;
}

// 获取最大 id, 最小 id
xn.arrlist_min = function(arrlist, key) {
        var minid = 99999999999;
         arrlist.map(function(v) {
                if(v[key] < minid) {
                        minid = v[key];
                }
        });
        return minid;
}


// 组件
Vue.component('comp-pm', {
	props: ['pm', 'is_last', 'user', 'cuser'],
	template: '#tpl_pm',
        inherit: true,
	methods: {
	  	delete_pm: function(pm) {
	  		if(!window.confirm('确定删除？')) return;
                        $.xpost(xn.url('pm-delete'), {pmid: pm.pmid}, function(code, message) {
                                if(code == 0) {
                                        var index = app.pmlist.indexOf(pm); 
			                app.pmlist.splice(index, 1);
                                } else {
                                        alert(message);
                                }
                        });
			//app.pmlist = app.pmlist.filter(t => t.pmid != 5)
			//app.pmlist.$remove(pm); // vue 2.0 废弃
	  	}
  	}
});

app = new Vue({
	el: '#pm_dialog',
	data: {
                uid: uid,
                cuid: 0,
                cuser: {},
                user: user,
                recentlist: [],        // 最近联系人列表 = 临时发起对话的列表 + 从服务端获取的列表
                recent_active_list: [],  // 临时发起对话的列表
                recent_request_list: [], // 从服务端获取的列表
                pmlist: [],
                pmlists: {},            // 用来缓存短消息列表
                maxids: {},           // 最大的 pmid
                minids: {},           // 最小的 pmid
                textarea: '',
                recent_loading: -1,      // -1: 从未加载过，1: 正在加载 0: 加载完成
                pmlist_loading: -1,      // -1: 从未加载过，1: 正在加载 0: 加载完成
                have_more_pm: false,
	},
	computed: {
                recentlist: function() {
                        var arrlist = [];
                        //Array.prototype.push.apply(arrlist, this.recent_active_list);
                        //Array.prototype.push.apply(arrlist, this.recent_request_list);
                        arrlist = xn.arrlist_merge(this.recent_active_list, this.recent_request_list, 'uid');
                        return arrlist;
                }
	},
        watch: {
                cuid: function() {
                        if(!this.cuid) return;
                        var cuid = this.cuid;
                        var pmlists = this.pmlists;
                        
                        var _this = this;
                        var on_cuid_change = function(cuid) {
                                _this.pmlist = _this.pmlists["uid_"+cuid];
                                _this.cuser = _this.recentlist.find(function(user) { return user.uid == cuid; });
                        }
                        if(!pmlists["uid_"+cuid]) {
                                this.update_pm_list('gt', function(cuid) {
                                        on_cuid_change(cuid);
                                });
                        } else {
                                on_cuid_change(cuid);
                        }
                },
        },
	methods: {
                change_user: function(uid) {
                        this.cuid = uid;
                },
		create_pm: function(pmid) {
                        var postdata = {
                                touid: this.cuid,
                                message: this.textarea,
                        };
                        var _this = this;
                        $.xpost(xn.url('pm-create'), postdata, function(code, message) {
                                if(code != 0) return alert(message);
                                var pmid = message.pmid;
                                var newpm = {
                                        pmid: message.pmid,
                                        uid: user.uid,
                                        senduid: user.uid,
                                        username: user.username,
                                        avatar_url: user.avatar_url,
                                        create_date_fmt: '刚才',
                                        message: message.message
                                }
                                _this.pmlist.push(newpm);
                                Vue.nextTick(function() { 
                                        _this.textarea = '';
                                        _this.$refs.textarea.focus();
                                        _this.$refs.pmlist.scrollTop = 100000;
                                });
                        });
		},
                more_pm: function() {
                        // 获取更多短消息
                        this.update_pm_list('lt');
                },
                // 更新最近联系人列表
                update_recent_list: function(callback) {
                        this.recent_loading = 1;
                        var _this = this;
                        $.xget(xn.url('pm-recent_list'), function(code, message) {
                                if(code == 0) {
                                        _this.recent_request_list = message;
                                        if(callback) callback(message);
                                }
                                _this.recent_loading = 0;
                        });
                },
                // 更新短消息列表, cuid, pmid, callback
                update_pm_list: function(op, callback) {
                        var cuid = this.cuid;
                        if(!cuid) return;
                        
                        // 取最新的
                        if(op == 'gt') {
                                var minid = this.maxids['uid_'+cuid] || 0;
                                pmid = minid;
                        } else {  //  if(op == 'lt') 
                                var maxid = this.minids['uid_'+cuid] || 99999999999;
                                pmid = maxid;
                        }

                        this.pmlist_loading = 1;
                        var _this = this;
                        
                        // 每次取 20 条
                        $.xget(xn.url('pm-list-'+uid+'-'+cuid+'-'+op+'-'+pmid), function(code, message) {
                                if(code == 0) {
                                        var pmlist = _this.pmlists["uid_"+cuid] || [];
                                        if(op == 'gt') {
                                                pmlist.push.apply(pmlist, message);
                                                var maxid = xn.arrlist_max(pmlist, 'pmid');
                                                Vue.set(_this.maxids, 'uid_'+cuid, maxid);
                                                // 如果没有最小id，则更新最小 id
                                                if(!minid) {
                                                        minid = xn.arrlist_min(pmlist, 'pmid');
                                                        Vue.set(_this.minids, 'uid_'+cuid, minid);
                                                }
                                                Vue.nextTick(function() { 
                                                        _this.$refs.pmlist.scrollTop = 100000;
                                                });
                                        } else { //  if(op == 'lt') 
                                                pmlist.unshift.apply(pmlist, message);
                                                var minid = xn.arrlist_min(pmlist, 'pmid');
                                                Vue.set(_this.minids, 'uid_'+cuid, minid);
                                                Vue.nextTick(function() {
                                                        _this.$refs.pmlist.scrollTop = 0;
                                                });
                                        }

                                        _this.have_more_pm = message.length > 10 ? true : false;

                                        Vue.set(_this.pmlists, "uid_"+cuid, pmlist);

                                        if(callback) callback(cuid, message);
                                } else {
                                        alert(message);
                                }
                                _this.pmlist_loading = 0;
                        });
                },
                add_recent_active_user: function(u) {
                        if(!u || !u.uid) return;
                        // 需要去除重复
                        if(this.recent_active_list.findIndex(function(v) { return v.uid == u.uid; }) == -1) {
                                //alert(u.uid);
                                this.recent_active_list.unshift({
                                        uid: u.uid,
                                        username: u.username,
                                        avatar_url: u.avatar_url,
                                        count: 0
                                });
                        }
                }
	},
       /*
        updated: function() {

	},
        // 窗口弹出的时候才需要初始化
        mounted: function() {
                //this.change_user(1);
        }*/
});
//app.change_user(1);



// 定时请求数据
var xn_loop_get = function(url, callback) {
        this.url = url;
        this.callback = callback;
};
xn_loop_get.prototype.init_delay = debug ? 5 : 4;
xn_loop_get.prototype.delay = xn_loop_get.prototype.init_delay;
xn_loop_get.prototype.t = null;
xn_loop_get.prototype.cleartimeout = function() {
        if(this.t) {
                clearTimeout(this.t);
                this.t = null;
        }
}
xn_loop_get.prototype.request = function(n) {
        var _this = this;
        this.cleartimeout();
        this.t = setTimeout(function() {
                $.xget(_this.url, function(code, message) {
                       // 表示没有消息，延长请求的时间
                        if(code == 0) {
                                _this.delay *= 2;
                                _this.callback(message);
                        // 如果有消息，则缩短消息更新的时间。
                        } else if(code == 1) {
                                _this.delay = _this.init_delay;
                                _this.callback(message);
                        // 如果发生错误，延迟变得更长
                        } else {
                                _this.delay *= 4;
                        }
                        _this.request();
                });
        }, (n !== undefined ? n : this.delay) * 1000);
};

// 重设 loop 时间
xn_loop_get.prototype.set_delay = function(seconds) {
        //seconds = xn.intval(seconds);
        if(this.delay > seconds) {
                this.delay = seconds;
                this.cleartimeout();
                this.request();
        }
}

// 定时请求是否有新消息。更新图标
var newpmreq = new xn_loop_get(xn.url('pm-new'), function(message) {
        // 如果发现对话框弹出了，则更新最近列表
        if(message == 0) {
                jpm_icon.removeClass('newpm');
        } else if(message > 0) {
                jpm_icon.addClass('newpm');
                // 如果对话框被弹出，加快请求节奏
                if(!$('#pm_dialog').is(':hidden')) {
                        // 取列表
                        app.update_recent_list();
                        app.update_pm_list('gt');
                // 如果对话框没弹出，放慢请求节奏
                } else {
                        newpmreq.set_delay(20);
                }
        }
});

// 对话框弹出，加快请求节奏
$('#pm_dialog').on('show.bs.modal', function () {
        newpmreq.request(0);
        newpmreq.set_delay(newpmreq.init_delay);
})

// 对话框关闭，放慢请求节奏
$('#pm_dialog').on('hidden.bs.modal', function () {
        newpmreq.set_delay(10);
})

newpmreq.request(0);
//$('#pm_dialog').modal('show');

// 给对方发但消息
// {uid: 3, username: "Locy", avatar_url: "view/img/3.png", count: 0}

// 如果 uid 不在 recent_list 中，则远程获取用户信息，并且放入到 active_list 当中
function show_pm_dialog(cuid) {

        var func = function() {
                 // 指定某一个用户
                if(cuid) {
                        app.cuid = cuid;
                // 默认第一个用户，前面是异步 todo:
                } else {
                        app.cuid = app.recentlist.length > 0 ? app.recentlist[0].uid : 0;
                }
        }
        // 如果为初始化过，则初始化
        if(app.recent_loading == -1) {
                // 从服务端获取最近联系人
                app.update_recent_list(function() {
                        func();
                });
        } else {
               func();
        }

        $('#pm_dialog').modal('show');

        return false;
}
</script>

<?php } ?>